package cn.itcast.service.impl;

import cn.itcast.entity.PageResult;
import cn.itcast.entity.QueryPageBean;
import cn.itcast.mapper.UserMapper;
import cn.itcast.pojo.Role;
import cn.itcast.pojo.User;
import cn.itcast.service.UserService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;


@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    public User findByName(String name) {

        return userMapper.findByName(name);
    }


    /**
     *  用户管理-分页查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean)  {

        //PageHelper.startPage(当前页，每页显示条数)
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());

        //将查询的结果封装为集合对象
        List<User> list = userMapper.findPage(queryPageBean.getQueryString());

        //将集合载入到PageInfo中，反推中总记录数
        PageInfo info = new PageInfo(list);

        //返回总页数，和list集合
        return new PageResult(info.getTotal(),list);
    }


    /**
     * 用户管理-新增用户
     * @param user
     */
    @Override
    public void add(User user) {

        //存入数据库密码加密
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

        String password = encoder.encode(user.getPassword());

        user.setPassword(password);

        userMapper.add(user);

    }

    /**
     * 用户管理-根据用户id查询对应的角色
     * @param id
     * @return
     */
    @Override
    public List<Role> findRoleIdByUserId(Integer id) {

        List<Role> roles = userMapper.findRoleIdByUserId(id);

        return roles;
    }


    /**
     * 用户管理-给用户添加角色
     * @param uid
     * @param roleIds
     */
    @Override
    public void addRole(Integer uid, Integer[] roleIds) {

        for (Integer roleId : roleIds) {

            userMapper.addRole(uid,roleId);

        }


    }

    /**
     * 文件下载-查询所有用户
     * @return
     */
    @Override
    public List<Map<String, Object>> findUserManagement() {

        return userMapper.findUserManagement();
    }


    /**
     * 用户管理-根据id删除用户
     * @param id
     */
    @Override
    public void deleteUserById(Integer id) {

        Integer count = userMapper.findRoleIds(id);



        if (count > 0){

            userMapper.deleteUserIdAndRoleId(id);

        }

        userMapper.deleteUserById(id);

    }


    @Override
    public List<User> findByRoleId(int id) {
        return userMapper.findByRoleId(id);
    }
}
